
//
//  GoodsOrderRootFirstVC.m
//  EasyToTesco2.0
//
//  Created by 杨森 on 16/9/3.
//  Copyright © 2016年 EasyToTesco. All rights reserved.
//

#import "GoodsOrderRootFirstVC.h"
#import "GoodsOrderModel.h"
#import "GoodsListsModel.h"
#import "GoodsOrderInfoCell.h"


@interface GoodsOrderRootFirstVC ()
<UITableViewDelegate,UITableViewDataSource>
{
    MBProgressHUD *progressHUD;
    UIImageView *noDrawImage;
    NSUInteger refreshIndex;
    NSDictionary *_picprex;
}

@property(nonatomic,strong)UITableView *goodsView;

@property(nonatomic,strong)NSMutableArray *goodsOrderArray;

@end

@implementation GoodsOrderRootFirstVC

static NSString * const goodsOrderReuseIdentifier =  @"OrderFirstCell";


#pragma mark >>>>>>>>>>>>>>>>>>>全部
- (void)viewDidLoad {
    [super viewDidLoad];
    
    refreshIndex = 1;
    
    [self buildView];
    [self goodsOrderListRequestData:refreshIndex];
}

- (void)buildView
{
    
    self.goodsView = [[UITableView alloc] initWithFrame:CGRectMake(0,0,WIDTH,HEIGHT-116 ) style:UITableViewStyleGrouped];
    [self.view addSubview:_goodsView];
    _goodsView.delegate = self;
    _goodsView.dataSource = self;
    _goodsView.rowHeight = 80;
    _goodsView.backgroundColor = BACKGROUND_COLOR;
    
    
    [self goodsOrderDataRefreshing];
}

#pragma mark >>>>>>>>刷新
- (void)goodsOrderDataRefreshing
{
    //上啦刷新
    _goodsView.mj_footer = [TopPullRefreshAnaimation footerWithRefreshingTarget:self refreshingAction:@selector(goodsOrderListRequestMoreData)];
    
    //下拉刷新
    MJChiBaoZiHeader *header = [MJChiBaoZiHeader headerWithRefreshingTarget:self refreshingAction:@selector(goodsOrderListRequesetDownData)];
    
    // 隐藏时间 和状态
    header.lastUpdatedTimeLabel.hidden = YES;
    header.stateLabel.hidden = YES;
    //
    //    [header beginRefreshing];
    //    _goodsView.mj_header = header;
    
}


//上啦更多
- (void)goodsOrderListRequestMoreData
{
    refreshIndex ++;
    [self goodsOrderListRequestData:refreshIndex];
    [_goodsView.mj_footer endRefreshing];
}

- (void)goodsOrderListRequesetDownData
{
    refreshIndex =1;
    [self goodsOrderListRequestData:refreshIndex];
    [_goodsView.mj_header endRefreshing];
}

#pragma mark >>>>>>>>>获取商品列表
- (void)goodsOrderListRequestData:(NSInteger)index
{
    
    //菊花加载
    progressHUD = [MBProgressHUD loadingInformationToView];
    [self.view addSubview:progressHUD];
    
    //避免下拉刷新重复数据
    if (refreshIndex ==1) {
        [self.goodsOrderArray removeAllObjects];
    }
    
    NSDictionary *dict = @{@"username":USERNAME,@"page":[NSString stringWithFormat:@"%zd",index],@"zt":@(0)};
    //    NSLog(@"%@",dict);
    
    [[NetWorkSharedTools sharedNetWorkTools] objectWithURLDict:dict AndMenthodName:@"/api/Order/getShopGoodsList" completeBlock:^(id object) {
        
//        NSLog(@"---------------%@",object);
        if (JudgeBackDataCode) {
            
            NSDictionary *tempDict = [object objectForKey:@"data"];
            _picprex = [tempDict objectForKey:@"picprex"];
            NSArray *tempArr = [tempDict objectForKey:@"order_list"];
            
            for (NSDictionary *tempDict in tempArr) {
                GoodsOrderModel *goodsOrderModel = [[GoodsOrderModel alloc] initWithDictionary:tempDict error:nil];
                if (goodsOrderModel) {
                    [self.goodsOrderArray addObject:goodsOrderModel];
                }
            }
            
        }else{
            
            //订单没有
            if (refreshIndex == 1) {
                noDrawImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"noOrder"]];
                [self.view addSubview:noDrawImage];
                
                [noDrawImage mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.centerX.equalTo(self.view.mas_centerX);
                    make.centerY.equalTo(self.view.mas_centerY).offset(-HEIGHT/8);
                    make.width.mas_equalTo(WIDTH/2);
                    make.height.mas_equalTo(HEIGHT/4);
                }];
            }else{
                
                //没有更多数据
                [_goodsView.mj_footer endRefreshingWithNoMoreData];
                
            }
            
        }
        [progressHUD hide:YES];
        [_goodsView reloadData];
        progressHUD.removeFromSuperViewOnHide = true;
        
    }];
    
}

- (void)deleteUserGoodsOrderRequestDataOrder_id:(NSString *)order_id
{
    
    NSDictionary *params = @{@"username":USERNAME,@"order_id":order_id};
    
    [[NetWorkSharedTools sharedNetWorkTools] objectWithURLDict:params AndMenthodName:@"/api/Order/deleteOrder" completeBlock:^(id object) {
        
        NSLog(@"%@",object);
        if (JudgeBackDataCode) {
            
            progressHUD = [MBProgressHUD showMessage:@"订单删除成功" toView:self.view dimBackground:NO AndCompleteBlock:^(id object) {
                
                [self goodsOrderListRequestData:1];
            }];
            
            [self.view addSubview:progressHUD];
            
        }else{
            
            NSDictionary *dict = [object objectForKey:@"message"];
            MBProgressHUD *hud = [MBProgressHUD showMessage:dict[@"view"] toView:self.view dimBackground:NO AndCompleteBlock:nil];
            [self.view addSubview:hud];
        }
        
    }];
}


#pragma mark 支付  删除 按钮
- (void)goodsOrderPayDidClick:(UIButton *)sender
{
    GoodsOrderModel *goodsModel = self.goodsOrderArray[sender.tag];
    NSArray *goodlistArr = goodsModel.goods_list;
    //limit_buy
    GoodsListsModel *goodsListsModel = goodlistArr[0];
    NSString *order_id = goodsModel.dxh;
    
    NSDictionary *userDict = @{@"orderId":order_id,@"zongjia":goodsModel.zongjia,@"limit_buy":goodsListsModel.limit_buy};
    
    [[NSNotificationCenter defaultCenter] postNotificationName:NOTIFICATION_ORDER_PAY object:nil userInfo:userDict];
    
}

-(void)deleteUserGoodsOrderClick:(UIButton *)sender
{
    GoodsOrderModel *goodsModel = self.goodsOrderArray[sender.tag];
    //弹框
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"确定删除此订单吗?" preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *okay = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //菊花加载
        progressHUD = [MBProgressHUD loadingInformationToView];
        [self.view addSubview:progressHUD];
        
        //删除请求
        [self deleteUserGoodsOrderRequestDataOrder_id:goodsModel.dxh];
        
        [progressHUD hide:YES];
        progressHUD.removeFromSuperViewOnHide = true;
    }];
    UIAlertAction *cancle = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"取消");
    }];
    
    [alert addAction:okay];
    [alert addAction:cancle];
    [self presentViewController:alert animated:YES completion:nil];
}


#pragma mark >>>>>>>>>>数据源
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    
    return self.goodsOrderArray.count;
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    GoodsOrderModel *goodsOrderModel = self.goodsOrderArray[section];
    NSArray *listArr = goodsOrderModel.goods_list;
    return listArr.count;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    GoodsOrderInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:goodsOrderReuseIdentifier ];
    
    if (cell == nil) {
        cell = [[GoodsOrderInfoCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:goodsOrderReuseIdentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
    }
    
    GoodsOrderModel *goodsOrderModel = self.goodsOrderArray[indexPath.section];
    NSArray *goodlistArr = goodsOrderModel.goods_list;
    GoodsListsModel *goodsListsModel = goodlistArr[indexPath.row];
//    NSLog(@"goodsListsModel %@",goodsListsModel);
    
 
    //图片
    [cell.goodsImg sd_setImageWithURL:[NSURL URLWithString:goodsListsModel.picurl] placeholderImage:[UIImage imageNamed:@"goodsLoadJGG"]];
    
    cell.goodsName.text = goodsListsModel.title;
    cell.goodsPrice.text = [NSString stringWithFormat:@"¥%@",goodsListsModel.jiage];
    cell.goodsNum.text = [NSString stringWithFormat:@"x%@",goodsListsModel.nums];
    
    cell.guige.text = [self getGoodsOrderStandardStrIndexPath:indexPath];
    
    return cell;
}

#pragma mark 返回商品规格字符串
- (NSString *)getGoodsOrderStandardStrIndexPath:(NSIndexPath *)indexPath
{
    GoodsOrderModel *goodsOrderModel = self.goodsOrderArray[indexPath.section];
    NSArray *goodlistArr = goodsOrderModel.goods_list;
    GoodsListsModel *goodsListsModel = goodlistArr[indexPath.row];
    
    
    NSMutableArray *arr = [[NSMutableArray alloc] init];
    NSString *tempStr = nil;
    if (![goodsListsModel.guige isEqualToString:@"(null)"]) {
        tempStr = [NSString stringWithFormat:@"规格:%@ ",goodsListsModel.guige];
        [arr addObject:tempStr];
    }
    if (![goodsListsModel.xinghao isEqualToString:@"(null)"]) {
        tempStr = [NSString stringWithFormat:@"型号:%@ ",goodsListsModel.xinghao];
        [arr addObject:tempStr];
    }
    if (![goodsListsModel.yscontent isEqualToString:@"(null)"]) {
        tempStr = [NSString stringWithFormat:@"%@ ",goodsListsModel.yscontent];
        [arr addObject:tempStr];
    }
    if (![goodsListsModel.feilv isEqualToString:@"(null)"]) {
        tempStr = [NSString stringWithFormat:@"费率:%@ ",goodsListsModel.feilv];
        [arr addObject:tempStr];
    }
    if (![goodsListsModel.kouwei isEqualToString:@"(null)"]) {
        tempStr = [NSString stringWithFormat:@"口味:%@ ",goodsListsModel.kouwei];
        [arr addObject:tempStr];
    }
    if (![goodsListsModel.chima isEqualToString:@"(null)"]) {
        tempStr = [NSString stringWithFormat:@"尺码:%@ ",goodsListsModel.chima];
        [arr addObject:tempStr];
    }
    if (![goodsListsModel.yanse isEqualToString:@"(null)"]) {
        tempStr = [NSString stringWithFormat:@"颜色:%@ ",goodsListsModel.yanse];
        [arr addObject:tempStr];
    }
    if (![goodsListsModel.taocan isEqualToString:@"(null)"]) {
        tempStr = [NSString stringWithFormat:@"套餐:%@ ",goodsListsModel.taocan];
        [arr addObject:tempStr];
    }
    
    
    NSMutableString * string = [[NSMutableString alloc] init];
    for (NSString *str in arr) {
        [string appendString:str];
    }
    
    return string;
}

#pragma mark 代理

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    GoodsOrderModel *goodsModel = self.goodsOrderArray[indexPath.section];
    NSString *zt = goodsModel.zt;
    [[NSNotificationCenter defaultCenter] postNotificationName:NOTIFICATION_ORDER_DETAILS object:nil userInfo:@{@"zt":zt,@"model":goodsModel,@"picprex":_picprex[@"s"]                                  }];
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    GoodsOrderModel *goodsOrderModel = self.goodsOrderArray[section];
    
    UIView *headView = [[UIView alloc] init];
    headView.backgroundColor = [UIColor whiteColor];
    
    //订单状态
    UILabel *stutasLabel = [[UILabel alloc] init];
    stutasLabel.font = FONT(13);
    [headView addSubview:stutasLabel];
    stutasLabel.textColor = DEFAULT_COLOR;
    if ([goodsOrderModel.zt isEqualToString:@"1"]) {
        stutasLabel.text = @"已付款";
    }else if ([goodsOrderModel.zt isEqualToString:@"2"]){
        stutasLabel.text = @"已退款";
    }else if([goodsOrderModel.zt isEqualToString:@"0"]){
        stutasLabel.text = @"未付款";
    }else{
        stutasLabel.text = @"未知状态";
    }
    
    //时间
    UILabel *timeLabel = [[UILabel alloc] init];
    timeLabel.font = FONT(13);
    [headView addSubview:timeLabel];
    timeLabel.textColor = [UIColor grayColor];
    timeLabel.text = goodsOrderModel.addtime;
    
    
    [stutasLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.centerY.equalTo(headView.mas_centerY);
        make.left.equalTo(headView.mas_left).offset(10);
    }];
    [timeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(headView.mas_centerY);
        make.right.equalTo(headView.mas_right).offset(-10);
    }];
    
    return headView;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    GoodsOrderModel *goodsOrderModel = self.goodsOrderArray[section];
    
    UIView *headView = [[UIView alloc] init];
    headView.backgroundColor = [UIColor whiteColor];
    
    UILabel *postLbl = [[UILabel alloc] init];
    postLbl.font = FONT(12);
    postLbl.textColor = [UIColor grayColor];
    [headView addSubview:postLbl];
    postLbl.text = [goodsOrderModel.postage_amount integerValue] > 0 ? [NSString stringWithFormat:@"运费:%@元 总计:",goodsOrderModel.postage_amount] :  @"包邮 总计:";
    
    UILabel *totalLbl = [[UILabel alloc] init];
    totalLbl.font = FONT(15);
    totalLbl.font = [UIFont boldSystemFontOfSize:15];
    [headView addSubview:totalLbl];
    totalLbl.textColor = DEFAULT_COLOR;
    totalLbl.text = [NSString stringWithFormat:@"¥%@",goodsOrderModel.zongjia];
    
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0,40,WIDTH,1)];
    lineView.backgroundColor = [UIColor blackColor];
    lineView.alpha = 0.1;
    [headView addSubview:lineView];
    
    //立即付款
    if ([goodsOrderModel.zt isEqualToString:@"0"]) {
        
        UIButton *payBtn = [[UIButton alloc] init];
        [headView addSubview:payBtn];
        payBtn.tag = section;
        [payBtn setTitle:@"付款" forState:UIControlStateNormal];
        [payBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        payBtn.titleLabel.font = FONT(12);
        payBtn.layer.cornerRadius = 3;
        payBtn.layer.masksToBounds = YES;
        payBtn.layer.borderWidth = 0.5;
        payBtn.backgroundColor = DEFAULT_COLOR;
        payBtn.layer.borderColor = [UIColor whiteColor].CGColor;
        [payBtn addTarget:self action:@selector(goodsOrderPayDidClick:) forControlEvents:UIControlEventTouchUpInside];
        [payBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            
            make.width.mas_equalTo(60);
            make.height.mas_equalTo(25);
            make.centerY.equalTo(headView.mas_centerY).offset(15);
            make.right.equalTo(headView.mas_right).offset(-10);
        }];
    }
    //删除此订单
    if ([goodsOrderModel.zt isEqualToString:@"0"]) {
        
        UIButton *deleteBtn = [[UIButton alloc] init];
        [headView addSubview:deleteBtn];
        deleteBtn.tag = section;
        [deleteBtn setTitle:@"删除订单" forState:UIControlStateNormal];
        [deleteBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        deleteBtn.titleLabel.font = FONT(12);
        deleteBtn.layer.cornerRadius = 3;
        deleteBtn.layer.masksToBounds = YES;
        deleteBtn.layer.borderWidth = 0.5;
        deleteBtn.layer.borderColor = [UIColor grayColor].CGColor;
        [deleteBtn addTarget:self action:@selector(deleteUserGoodsOrderClick:) forControlEvents:UIControlEventTouchUpInside];
        
        [deleteBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            
            make.width.mas_equalTo(70);
            make.height.mas_equalTo(25);
            make.centerY.equalTo(headView.mas_centerY).offset(15);
            
            if ([goodsOrderModel.zt isEqualToString:@"0"]) {
                make.right.equalTo(headView.mas_right).offset(-80);
            }else{
                make.right.equalTo(headView.mas_right).offset(-10);
            }
        }];
        
        
    }
    
    UIView *separateView = [[UIView alloc] init];
    separateView.backgroundColor = BACKGROUND_COLOR;
    [headView addSubview:separateView];
    
    [separateView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(WIDTH);
        make.height.mas_equalTo(10);
        make.bottom.equalTo(headView.mas_bottom);
    }];
    
    
    [totalLbl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(headView.mas_centerY).offset(-20);
        make.right.equalTo(headView.mas_right).offset(-10);
    }];
    
    [postLbl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(totalLbl.mas_centerY);
        make.right.equalTo(totalLbl.mas_left).offset(-5);
    }];
    
    return headView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 40;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 90;
}

- (NSMutableArray *)goodsOrderArray
{
    if (!_goodsOrderArray) {
        
        _goodsOrderArray= [NSMutableArray array];
    }
    return _goodsOrderArray;
}


@end
